package com.shigen.file.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.shigen.file.common.Result;
import com.shigen.file.entity.Project;
import com.shigen.file.req.ProjectRequest;
import com.shigen.file.req.ProjectRequest.DownloadDataReq;
import com.shigen.file.req.ProjectRequest.QueryByName;
import com.shigen.file.req.ProjectRequest.UpdateStatusReq;
import com.shigen.file.res.ProjectResponse.PageResponse;
import com.shigen.file.service.IProjectService;
import io.swagger.annotations.ApiOperation;
import java.io.IOException;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 问卷收集表 前端控制器
 * </p>
 *
 * @author shigen.fu
 * @since 2022-06-04
 */
@RestController
@RequestMapping("/project")
public class ProjectController {

  @Resource
  private IProjectService projectService;

  /**
   * 根据问卷名称分页查询问卷，名称为空表示查询全部分页
   */
  @PostMapping(value = "queryByName")
  public Result<IPage<PageResponse>> queryByName(@RequestBody @Valid QueryByName queryByName) {
    return Result.success(projectService.queryByName(queryByName));
  }

  @PostMapping(value = "create")
  @ApiOperation(value = "创建新的表单项目")
  public Result<String> insert(@RequestBody @Valid ProjectRequest.Create create) {
    int i = projectService.createProject(create);
    return i > 0 ? Result.success("成功") : Result.err("失败");
  }

  /**
   * 表单项目的查询
   */
  @GetMapping(value = "get/{id}")
  @ApiOperation(value = "表单项目的查询")
  public Result<Project> getProject(@PathVariable String id) {
    return Result.success(projectService.getProjectById(id));
  }

  /**
   * 更新表单的状态
   */
  @PutMapping(value = "update")
  @ApiOperation(value = "开启和停止表单的收集")
  public Result<String> updateProjectStatus(@RequestBody @Valid UpdateStatusReq updateStatusReq) {
    int i = projectService.changeProjectStatus(updateStatusReq.getProjId(), updateStatusReq.getStatus());
    return i > 0 ? Result.success("操作成功") : Result.err("操作失败");
  }

  /**
   * 下载表单数据
   */
  @PostMapping(value = "download")
  @ApiOperation(value = "下载表单数据")
  public void download(@RequestBody @Valid DownloadDataReq downloadDataReq, HttpServletResponse response) throws IOException {
    projectService.downloadData(downloadDataReq.getProjId(), downloadDataReq.getWithAdditionInfo(), response);
  }
}
